import './style.scss'
import { useEffect, useRef, useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import type { ResponseType } from './types';
import useRequest from '../../hooks/useRequest';
// 获取缓存的location经纬度
const localLocation = localStorage.getItem('location');
const locationHistory = localLocation ? JSON.parse(localLocation) : null;
  // 默认请求数据
const defaultRequestData = {
  url: '/nearby.json',
  method: 'POST',
  data: {
    latitude: locationHistory ? locationHistory.latitude : 37.7304167, // 纬度
    longitude: locationHistory ? locationHistory.longitude : -122.384425 // 经度
  }
}
const Nearby = () => {
  const { data } = useRequest<ResponseType>(defaultRequestData);
  const [keyword, setKeyword] = useState('');
  const navigate = useNavigate();
  // console.log('data=', data);
  const list = (data?.data || []).filter(item => {return item.name.indexOf(keyword) > -1});
  function handleItemClick (latitude: string, longitude:string){
    localStorage.setItem('location', JSON.stringify({
      latitude, longitude
    }))
    navigate('/home')
  }
  return (
    <div className="page nearby-page">
      <div className="title">
        <Link to='/home'>
          <div className="iconfont title-icon" >&#xe600;</div>
        </Link>
        
        切换门店</div>
      <div className="search">
        <div className="search-icon iconfont">&#xe6c5;</div>
        <input type="text" value={keyword} className="search-input" placeholder='请输入地址' onChange={(e)=>{setKeyword(e.target.value)}} />
      </div>
      <div className="subtitle">附近门店</div>
      <ul className='list'>
        {
          list.map(item =>{
            return (
              <li className='list-item' key={item.id} onClick={()=>{handleItemClick(item.latitude, item.longitude)}} >
                <div className="list-item-left">
                  <div className="list-item-title">{item.name}</div>
                  <div className="list-item-desc">联系电话：{item.phone}</div>
                  <div className="list-item-desc">{item.adderss}</div>
                </div>
                <div className="list-item-right">
                  <span className="iconfont list-item-distance">&#xe67c;</span>{item.distance}
                </div>
              </li>
            )
          })
        }
      </ul>
    </div>
  )
}

export default Nearby;